/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sentry.commons.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 
 * 属性文件读取工具，支持从system property 指定变量<code>config.path</code>配置绝对路径，<br>
 * 如果没有指定则使用classpath下的/config.properties
 * 
 * @author WuBo (wub1@minshenglife.com)
 */
public class Props {

    private static Logger LOGGER = LoggerFactory.getLogger(Props.class);

    private static final Properties PROPERTIES = new Properties();;


    private static final String ARRAY_SEPARATOR = ",";
    
    private static final String CONFIG_PROP_NAME = "config.path";
    
    private static final String DEFAULT_CONFIG_PATH = "/config.properties";

    private Props() {}

    /**
     * 取出Property。
     */
    public static String getValue(String key) {
        return getValue(key, null);
    }

    /**
     * 带有默认值的取出
     * 
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getValue(String key, final String defaultValue) {
        return PROPERTIES.getProperty(key, defaultValue);
    }



    public static Integer getInteger(String key) {
        return Integer.valueOf(getValue(key));
    }


    public static Double getDouble(String key) {
        return Double.valueOf(getValue(key));
    }


    public static Boolean getBoolean(String key) {
        return Boolean.valueOf(getValue(key));
    }


    /**
     * 返回一个String数组
     * 
     * @param key
     * @param separator 分隔符
     * @return
     */
    public static String[] getArray(String key, String separator) {
        String arrVal = getValue(key);
        if (StringUtils.isNotEmpty(arrVal)) {
            return StringUtils.split(arrVal, separator);
        }
        return null;
    }

    /**
     * 返回一个String数组，默认使用,作为分割
     * 
     * @param key
     * @return
     */
    public static String[] getArray(String key) {
        return getArray(key, ARRAY_SEPARATOR);
    }

    /**
     * 初始化一个配置文件
     */
    public synchronized static void init() {
        String configFilePath = System.getProperty(CONFIG_PROP_NAME, DEFAULT_CONFIG_PATH);
        init(configFilePath);
    }

 
    /**
     * 指定一个绝对路径进行初始化
     * @param absPath
     * @throws IOException 
     */
    public synchronized static void init(String absPath) {

        LOGGER.debug("开始加载配置文件[{}]", absPath);


        try(InputStream is = Props.class.getResourceAsStream(absPath)){
            PROPERTIES.load(is);
        } catch (IOException e) {
            LOGGER.error("读取配置文件[{}]异常", absPath, e);
        }
    }
}
